package myreactor;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class MyReactor implements Runnable{

	private Selector selector;
	private  Executor selectorPool;
	public MyReactor() {
		try {
			selector = Selector.open();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void start(String name) {
		selectorPool = Executors.newFixedThreadPool(1, new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
			    Thread mainThread = new Thread(r);
				mainThread.setName(name);
				return mainThread;
			}
		});
		selectorPool.execute(this);
	}
	
	@Override
	public void run() {
		
		while(!Thread.interrupted()) {
			try {
				selector.select();
				Set<SelectionKey> selectedKeys = selector.selectedKeys();
				Iterator<SelectionKey> itr = selectedKeys.iterator();
				while(itr.hasNext()) {
					SelectionKey selectionKey = itr.next();
					AbstractHandler handler = (AbstractHandler) selectionKey.attachment();
					handler.handle(selectionKey);
				}
				selectedKeys.clear();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		
	}
	
	public Selector getSelector() {
		return selector;
	}

}
